package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dtos.LikesBehaviorDto;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.message.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApThreadLocal;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String ,String> kafkaTemplate;

    /**
     * 存储喜欢数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {

        //1.校验参数
        if (dto.getArticleId() == null ) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录用户id
        ApUser apUser = ApThreadLocal.getApUser();
        //表示未登录
        if(apUser==null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if(apUser.getId()==0){
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }

        //3. 查询当前用户是否已经点赞
            //定义redis的key
        String likes_key="USER_LIKES_"+dto.getArticleId();
        Boolean flag = redisTemplate.opsForHash().hasKey(likes_key, apUser.getId()+"");

        //4.如果已经点赞，并且正在执行点赞动作，直接返回
        if(flag && dto.getOperation()==0){
            return ResponseResult.okResult(AppHttpCodeEnum.LIKES_USER_END_SUCCESS);
        }


        UpdateArticleMess mess=new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
        mess.setArticleId(dto.getArticleId());
        //5.如果用户已经点赞，但是正在执行的是取消点赞，则删除redis和mongo
        if(flag && dto.getOperation()==1){
            //删除redis
            redisTemplate.opsForHash().delete(likes_key,apUser.getId()+"");
            //删除mongo
            mongoTemplate.remove(
                    Query.query(Criteria.where("userId").is(apUser.getId()+"")
                    .and("articleId").is(dto.getArticleId()))
                    , ApLikesBehavior.class);
            //封装消息内容 add=-1
            mess.setAdd(-1);
            //发送消息
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));
            return ResponseResult.okResult(AppHttpCodeEnum.LIKES_USER_CANCEL_SUCCESS);
        }
        //6.如果用户没有点赞过，则正在执行的是点赞动作，则添加redis和mongo
        if(!flag && dto.getOperation()==0){
            //添加redis
            redisTemplate.opsForHash().put(likes_key,apUser.getId()+"","1");
            //添加mongo
            ApLikesBehavior apLikesBehavior=new ApLikesBehavior();
            apLikesBehavior.setId(ObjectId.get().toHexString());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setUserId(apUser.getId().longValue());
            apLikesBehavior.setType((short) 0);//默认是文章点赞
            mongoTemplate.insert(apLikesBehavior);
            //封装消息内容 add=1
            mess.setAdd(1);
            //发送消息
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));
            return ResponseResult.okResult(AppHttpCodeEnum.LIKES_USER_SUCCESS);
        }

        //7.返回数据
        return null;
    }
}
